﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class AgentOrder : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ToString());
    protected void Page_Init(object sender, EventArgs e)
    {

        int mounth=DateTime.Now.Month;
        if (mounth!=12&&mounth!=1&&mounth!=2)
        {
            Response.Redirect("AgentError.aspx");
        }

        if(!IsPostBack){
            
            //Session["sqlcon"] = sqlcon; //数据库连接
           
            Table Table_student = new Table();
            Session["Table_student"] = Table_student;   //输入的学生表
      

            Order order=new Order();
            order.Agent.AgentID = (String)Session["userId"];
            sqlcon.Open();
            order.Agent.fillDataById(sqlcon);
            sqlcon.Close();

            Session["Order"] = order;   //订单

           
            int num = 0;
            Session["num"] = num;
            int showholelnum = 0;
            Session["showholelnum"] = showholelnum; //记录输入的学生数目

            bool showseahotel=false;
            Session["showseahotel"] = showseahotel;  


            List<string> hotelIDlist=new List<string>();
            Session["hotelIDlist"] = hotelIDlist;
            
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "校园代理页面";
        Page.LoadControl("StudentInput.ascx");

        //日历显示与隐藏
       /* if (!Page.IsPostBack)
        {
            
            Calendar_start.Style.Add("display", "none");
            Calendar_end.Style.Add("display", "none");
            TextBox_starttime.Attributes.Add("onfocus", "document.getElementById('" + Calendar_start.ClientID + "').style.display=''");
            TextBox_endtime.Attributes.Add("onfocus", "document.getElementById('" + Calendar_end.ClientID + "').style.display=''");
        }
        */
        if ((Table)Session["Table_student"]!=null)
         PlaceHolder_student.Controls.Add((Table)Session["Table_student"]);

        createStudentInput();

        if (IsPostBack&&(bool)Session["showseahotel"])
        {
            createSeachhotel();
        }

    }
    
    

    protected void Button_studentnum_Click(object sender, EventArgs e)
    {
        createStudentInput();
    }

    protected void createStudentInput()
    {
        Session["num"] = 0;
        if (TextBox_studentnum.Text.ToString()!="")
            Session["num"] = Convert.ToInt32(TextBox_studentnum.Text.ToString());


        ((Table)Session["Table_student"]).Rows.Clear();
        ((Table)Session["Table_student"]).ID = "Table_student";


        for (int i = 0; i < (int)Session["num"]; i++)
        {

            UserControl stdi = (UserControl)Page.LoadControl("StudentInput.ascx");
            stdi.ID = "StudentInput" + i;


            TableRow tr = new TableRow();
            TableCell td = new TableCell();

            TableCell td1 = new TableCell();
            td1.Text = i + 1 + "";
            td.Controls.Add(stdi);
            tr.Cells.Add(td1);
            tr.Cells.Add(td);


            ((Table)Session["Table_student"]).Rows.Add(tr);

        }
    }

  
    

    protected void Button_ok_Click(object sender, EventArgs e)
    {
       // SqlConnection sqlcon = ((SqlConnection)Session["sqlcon"]);
       
        sqlcon.Open();
        if (checkOrder() == true) {//检测输入
                 //inputOrder(sqlcon); //录入

            string resultStr = ((Order)Session["Order"]).insert(sqlcon);

            if ("ok".Equals(resultStr))
            {
                Response.Write("<script language=javascript > alert('提交成功！'); window.open(\'AgentBackOrder.aspx\'); </script>");
               
            }
            else
            {
                Response.Write("<script language=javascript > alert('"+resultStr+"！');  </script>");
            }
            
            
        }
           

        sqlcon.Close();
    }

   
  

    protected bool checkOrder()
    {
       

        ((Order)Session["Order"]).Totalprice = 0;
        ((Order)Session["Order"]).RoomList.Clear();
        ((Order)Session["Order"]).StudenList.Clear();
        ((Order)Session["Order"]).Roomtypenum.Clear();

        if (Label_hotelname.Text == "")
        {
            Response.Write("<script language=javascript > alert('没有选择宾馆！');</script>");
            return false;
        }
      
        if ((int)Session["num"] == 0)
        {
            Response.Write("<script language=javascript > alert('学生人数为0！');</script>");
            return false;
        }


        string str1 = TextBox_room1.Text.ToString();
        string str2 = TextBox_room2.Text.ToString();
        string str4 = TextBox_room3.Text.ToString();
        string str3 = TextBox_room4.Text.ToString();

        if (str1 == "" && str2 == "" && str4 == "" && str3 == "")
        {
            Response.Write("<script language=javascript > alert('未输入房间数目！');</script>");
            return false;
        }
        RoomTypeNum rtm1;
        RoomTypeNum rtm2;
        RoomTypeNum rtm3;
        RoomTypeNum rtm4;

        if (str1 != "")
        {
            rtm1 = new RoomTypeNum(1, Convert.ToInt32(str1));
            ((Order)Session["Order"]).Roomtypenum.Add(rtm1);
        }
        if (str2 != ""){
            rtm2 = new RoomTypeNum(2, Convert.ToInt32(str2));
            ((Order)Session["Order"]).Roomtypenum.Add(rtm2);
         }
       
        
        

        if (str3 != "")
        {
            rtm3 = new RoomTypeNum(3, Convert.ToInt32(str3));
            ((Order)Session["Order"]).Roomtypenum.Add(rtm3);
        }

        if (str4 != "")
        {
            rtm4 = new RoomTypeNum(4, Convert.ToInt32(str4));
            ((Order)Session["Order"]).Roomtypenum.Add(rtm4);
        }
        



        
        


        DateTime mDataTimeChecktStart = new DateTime();
        DateTime mDataTimeChecktEnd = new DateTime();

        if (!DateTime.TryParse(TextBox_endtime.Text.ToString(),out mDataTimeChecktEnd) || !DateTime.TryParse(TextBox_starttime.Text.ToString(),out mDataTimeChecktStart))
        {
            Response.Write("<script language=javascript > alert('未输入日期！');</script>");
            return false;
        }

        //在这里做假期时间的检测，是否是在春节的时候

        if(!((mDataTimeChecktEnd.Month==12)||(mDataTimeChecktEnd.Month<=3))&&!((mDataTimeChecktStart.Month==12)||(mDataTimeChecktStart.Month<=3)))
        {
            Response.Write("<script language=javascript > alert('日期有误，月份不是规定的时间！');</script>");
            return false;
        }

        if (DateTime.Compare(DateTime.Now, mDataTimeChecktStart) >= 0 || DateTime.Compare(DateTime.Now, mDataTimeChecktEnd) >= 0)
        {
            Response.Write("<script language=javascript > alert('日期有误，不是未来日期！');</script>");
            return false;
        }

        if (DateTime.Compare(mDataTimeChecktStart, mDataTimeChecktEnd) > 0)
        {
            Response.Write("<script language=javascript > alert('起始日期大于结束日期！');</script>");
            return false;
        }
        //时间保存到Order对象
        ((Order)Session["Order"]).Starttime = TextBox_starttime.Text;
        ((Order)Session["Order"]).Endtime = TextBox_endtime.Text;


   
        for (int i = 0; i < (int)Session["num"]; i++)
        {
            Student student = new Student();

            Control asi = PlaceHolder_student.FindControl("StudentInput" + i);
            TextBox nameText = (TextBox)asi.FindControl("TextBox_name");
            student.Name = nameText.Text.ToString();
            student.SchoolID = ((Order)Session["Order"]).Agent.SchoolID;

            if(student.Name=="")
            {
                Response.Write("<script language=javascript > alert('" + (i + 1) + "号姓名为空！');</script>");
                return false;
            }

            TextBox birthdayText = (TextBox)asi.FindControl("TextBox_birthday");

            DateTime birthday;
           
            if (!DateTime.TryParse(birthdayText.Text, out birthday))
            {
                Response.Write("<script language=javascript > alert('" + (i + 1) + "出生日期有误！');</script>");
                return false;

            }

            student.Bitrhday = birthdayText.Text.ToString();

            RadioButton sexM = (RadioButton)asi.FindControl("RadioButton_M");
            RadioButton sexW = (RadioButton)asi.FindControl("RadioButton_W");

            if (sexM.Checked && !sexW.Checked)
            {
                student.Sex = 0;
            }
            else if (!sexM.Checked && sexW.Checked)
            {
                student.Sex = 1;
            }
            else
            {
                Response.Write("<script language=javascript > alert('" + (i+1) + "号性别为空！');</script>");
                return false;
            }

            TextBox IDText = (TextBox)asi.FindControl("TextBox_ID");
            student.IDCard1 = IDText.Text.ToString();
            if (student.IDCard1 == "")
            {
                Response.Write("<script language=javascript > alert('" + (i+1)+ "号身份证为空！');</script>");
                return false;
            }

            //检测身份证是否有重叠
            foreach (Student stu in ((Order)Session["Order"]).StudenList)
            {
                if (student.IDCard1 == stu.IDCard1)
                {
                    Response.Write("<script language=javascript > alert('" + (i + 1) + "号身份证重复！');</script>");
                    return false;
                }
            }
                   
            TextBox stdIDText = (TextBox)asi.FindControl("TextBox_studentID");
            student.StudentID = stdIDText.Text.ToString();
            if (student.StudentID == "")
            {
                Response.Write("<script language=javascript > alert('" + (i + 1) + "号学生证为空，是否忘记输入？');</script>");
                return false;
            
            }
            if (student.StudentID == "")
            {
                Response.Write("<script language=javascript > alert('" + (i + 1) + "号电话号码为空，是否忘记输入？');</script>");
                
            }

            ((Order)Session["Order"]).StudenList.Add(student);
            
        }

        Random mRandom = new Random();
         //设置订单ID
         string orderID = "OD" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + (mRandom.Next(10,99));

        ((Order)Session["Order"]).OrderID = orderID;
        return true;
    }






    //--------------------日历------------------
    protected void Calendar_start_SelectionChanged(object sender, EventArgs e)
    {
        TextBox_starttime.Text = Calendar_start.SelectedDate.ToShortDateString();
        Calendar_start.Visible = false;

    }
    protected void Calendar_end_SelectionChanged(object sender, EventArgs e)
    {
        TextBox_endtime.Text = Calendar_end.SelectedDate.ToShortDateString();
        Calendar_end.Visible = false;
    }

    protected void Button_starttime_Click(object sender, EventArgs e)
    {

        Calendar_start.Visible = Calendar_start.Visible?false:true;
    }
    protected void Button_endtime_Click(object sender, EventArgs e)
    {
        Calendar_end.Visible = Calendar_end.Visible ? false : true;
    }

    //确定选择宾馆
    protected void Button_selhotelOK_Click(object sender, EventArgs e)
    {
       // SqlConnection sqlcon = ((SqlConnection)Session["sqlcon"]);
        
        
        //查找宾馆，使用结果填充session 的hotel
        sqlcon.Open();

        SqlDataAdapter sqldat = new SqlDataAdapter();
        sqldat.SelectCommand = new SqlCommand("SELECT  * FROM HotelView WHERE hotelID=" + ap(DropDownList_hotel.SelectedValue)
            +" AND province="+ap(DropDownList_province.SelectedValue)
            +" AND city="+ap(DropDownList_city.SelectedValue)
            + " AND county=" + ap(DropDownList_county.SelectedValue) + ";", sqlcon);

        DataTable dt = new DataTable();
        sqldat.Fill(dt);

        if (dt.Rows.Count == 0)
        {
            sqlcon.Close();
            return;
        }
        ((Order)Session["Order"]).Hotel.HotelID = dt.Rows[0].ItemArray[0].ToString();
        ((Order)Session["Order"]).Hotel.Name = dt.Rows[0].ItemArray[1].ToString();
        ((Order)Session["Order"]).Hotel.Province = dt.Rows[0].ItemArray[2].ToString();
        ((Order)Session["Order"]).Hotel.City = dt.Rows[0].ItemArray[3].ToString();
        ((Order)Session["Order"]).Hotel.County = dt.Rows[0].ItemArray[4].ToString();
        ((Order)Session["Order"]).Hotel.Address = dt.Rows[0].ItemArray[5].ToString();

        Label_hoteltelnum.Text = dt.Rows[0].ItemArray[6].ToString();
        Label_hoteladdress.Text = dt.Rows[0].ItemArray[2].ToString()
                                +dt.Rows[0].ItemArray[3].ToString()
                                +dt.Rows[0].ItemArray[4].ToString()
                                + dt.Rows[0].ItemArray[5].ToString();
        Label_hotelname.Text = dt.Rows[0].ItemArray[1].ToString();
        ((Order)Session["Order"]).Hotel.Name = Label_hotelname.Text.ToString();
                               
        ((Order)Session["Order"]).Hotel.Telephonenumber = dt.Rows[0].ItemArray[6].ToString();
        ShowHotelFreeRoom(sqlcon);

        sqlcon.Close();



    }

    public void ShowHotelFreeRoom(SqlConnection sqlcon)
    {



        
        DataTable dt = Room.getFreeRoomCount(sqlcon, ((Order)Session["Order"]).Hotel.HotelID);

        if (dt == null)
            return;
       

        TableRow title = new TableRow();
        TableCell titletd1 = new TableCell();
        TableCell titletd2 = new TableCell();
        TableCell titletd3 = new TableCell();
        TableCell titletd4 = new TableCell();
        TableCell titletd5 = new TableCell();
        titletd1.Text = "可预订房间数量";
        titletd2.Text = "房间大小";
        titletd3.Text = "价格";
        titletd4.Text = "可预定时间";
        titletd5.Text = "至";
        title.Cells.Add(titletd1);
        title.Cells.Add(titletd2);
        title.Cells.Add(titletd3);
        title.Cells.Add(titletd4);
        title.Cells.Add(titletd5);
        Table_freeroom.Rows.Add(title);

        foreach (DataRow dr in dt.Rows)
        {
            TableRow tr = new TableRow();
            foreach (object ob in dr.ItemArray)
            {
                TableCell td = new TableCell();
                td.Text = ob.ToString();
                tr.Cells.Add(td);
            }
            Table_freeroom.Rows.Add(tr);

        }


        //string select = "SELECT top 100 roomname,startfreetime,endfreetime,roomsize,price FROM  RoomTable  WHERE hotelID="
        //    + ap(((Order)Session["Order"]).Hotel.HotelID)
        //    + " AND freestate=0 "
        //    + " AND endfreetime>="
        //    + ap(DateTime.Now.ToShortDateString());

        //SqlDataAdapter sqlapt = new SqlDataAdapter();
        //sqlapt.SelectCommand = new SqlCommand(select, sqlcon);
        //DataTable dt = new DataTable();
        //sqlapt.Fill(dt);

        //TableRow title = new TableRow();
        //TableCell titletd1 = new TableCell();
        //TableCell titletd2 = new TableCell();
        //TableCell titletd3 = new TableCell();
        //TableCell titletd4 = new TableCell();
        //TableCell titletd5 = new TableCell();
        //titletd1.Text = "可预订房间名";
        //titletd2.Text = "可以预订起始时间";
        //titletd3.Text = "可以预订结束时间";
        //titletd4.Text = "大小";
        //titletd5.Text = "价格";
        //title.Cells.Add(titletd1);
        //title.Cells.Add(titletd2);
        //title.Cells.Add(titletd3);
        //title.Cells.Add(titletd4);
        //title.Cells.Add(titletd5);
        //Table_freeroom.Rows.Add(title);

        //foreach (DataRow dr in dt.Rows)
        //{
        //    TableRow tr = new TableRow();
        //    foreach (object ob in dr.ItemArray)
        //    {
        //        TableCell td = new TableCell();
        //        td.Text = ob.ToString();
        //        tr.Cells.Add(td);
        //    }
        //    Table_freeroom.Rows.Add(tr);

        //}

    }

    protected void Button_searchhotel_Click(object sender, EventArgs e)
    {
        GridView_showhotel.Visible = true;

        /*
        if (TextBox_searchhotel.Text != "")
        {
            Session["showseahotel"] = true;
            createSeachhotel();
        }*/
        
    }

    protected void createSeachhotel() 
    {
           // SqlConnection sqlcon = ((SqlConnection)Session["sqlcon"]);
            sqlcon.Open();

            SqlDataAdapter sqldat = new SqlDataAdapter();

            string sqlstr = "SELECT TOP 20 * FROM HotelView WHERE hotelname like \'%" + TextBox_searchhotel.Text + "%\';";

            sqldat.SelectCommand = new SqlCommand(sqlstr, sqlcon);



            DataTable dt = new DataTable();

            sqldat.Fill(dt);
            Table_showhotel.Rows.Clear();
            Table_showhotel.Visible = true;
            Button_showhotel.Visible = true;
            Session["showholelnum"]= 0;
            ((List<string>)Session["hotelIDlist"]).Clear();

            foreach (DataRow dr in dt.Rows)
            {
                TableRow tr = new TableRow();

                TableCell tdname = new TableCell();
                TableCell tdprovince = new TableCell();
                TableCell tdcity = new TableCell();
                TableCell tdcounty = new TableCell();
                TableCell tdaddress = new TableCell();
                TableCell tdtelephonenumber = new TableCell();


                RadioButton rb = new RadioButton();
                rb.Text = dr[1].ToString();
                rb.ID = "RadioButton_selecthotelname" + (int)Session["showholelnum"];
                rb.GroupName = "RadioButton_selecthotelname";

            

                Label lbprovince = new Label();
                lbprovince.ID = "Label_selecthotelprovince" + (int)Session["showholelnum"];
                lbprovince.Text = dr[2].ToString();
               
                Label lbcity = new Label();
                lbcity.ID = "Label_selecthotelcity" + (int)Session["showholelnum"];
                lbcity.Text = dr[3].ToString();
             
                Label lbcounty = new Label();
                lbcounty.ID = "Label_selecthotelcounty" + (int)Session["showholelnum"];
                lbcounty.Text = dr[4].ToString();

                Label lbaddress = new Label();
                lbaddress.ID = "Label_selecthoteladdress" + (int)Session["showholelnum"];
                lbaddress.Text = dr[5].ToString();

                Label lbtelnum = new Label();
                lbtelnum.ID = "Label_selecthoteltelnum" + (int)Session["showholelnum"];
                lbtelnum.Text = dr[6].ToString();


       


                Session["showholelnum"] = (int)Session["showholelnum"] + 1;




                ((List<string>)Session["hotelIDlist"]).Add(dr[0].ToString());//宾馆ID

               
                tdname.Controls.Add(rb);  
                tdprovince.Controls.Add(lbprovince);  
                tdcity.Controls.Add(lbcity);  
                tdcounty.Controls.Add(lbcounty); 
                tdaddress.Controls.Add(lbaddress);
                tdtelephonenumber.Controls.Add(lbtelnum);  



                tr.Cells.Add(tdname);
                tr.Cells.Add(tdprovince);
                tr.Cells.Add(tdcity);
                tr.Cells.Add(tdcounty);
                tr.Cells.Add(tdaddress);
                tr.Cells.Add(tdtelephonenumber);

                Table_showhotel.Rows.Add(tr);
            }

            sqlcon.Close();
            
        
    }



    protected void Button_showhotel_Click(object sender, EventArgs e)
    {
     
        for (int i = 0; i < (int)Session["showholelnum"]; i++)
        {
            CheckBox cb = (CheckBox)Panel_showhotel.FindControl("RadioButton_selecthotelname" + i);
            if (cb.Checked)
            {
                Label_hotelname.Text = cb.Text;
                Label_hoteltelnum.Text = ((Label)Panel_showhotel.FindControl("Label_selecthoteltelnum" + i)).Text;


                Label_hoteladdress.Text = ((Label)Panel_showhotel.FindControl("Label_selecthotelprovince" + i)).Text
                                        + ((Label)Panel_showhotel.FindControl("Label_selecthotelcity" + i)).Text
                                        + ((Label)Panel_showhotel.FindControl("Label_selecthotelcounty" + i)).Text
                                        + ((Label)Panel_showhotel.FindControl("Label_selecthoteladdress" + i)).Text;

                ((Order)Session["Order"]).Hotel.Name = Label_hotelname.Text;
                ((Order)Session["Order"]).Hotel.HotelID = ((List<string>)Session["hotelIDlist"])[i];
                ((Order)Session["Order"]).Hotel.Province = ((Label)Panel_showhotel.FindControl("Label_selecthotelprovince" + i)).Text;
                ((Order)Session["Order"]).Hotel.City = ((Label)Panel_showhotel.FindControl("Label_selecthotelcity" + i)).Text;
                ((Order)Session["Order"]).Hotel.County =  ((Label)Panel_showhotel.FindControl("Label_selecthotelcounty" + i)).Text;
                ((Order)Session["Order"]).Hotel.Address = ((Label)Panel_showhotel.FindControl("Label_selecthoteladdress" + i)).Text;
                sqlcon.Open();
                ShowHotelFreeRoom(sqlcon);
                sqlcon.Close();
                break;
            }
        }


        Button_showhotel.Visible = false;
        Table_showhotel.Visible = false;
        Session["showseahotel"] = false;
    }

    protected string ap(string str)
    {
        return "\'"+str+"\'";
    }

    protected void GridView_showhotel_SelectedIndexChanged(object sender, EventArgs e)
    {
        

        Label_hotelname.Text = GridView_showhotel.SelectedRow.Cells[2].Text;
        Label_hoteltelnum.Text = GridView_showhotel.SelectedRow.Cells[7].Text;


        Label_hoteladdress.Text = GridView_showhotel.SelectedRow.Cells[3].Text
                                +GridView_showhotel.SelectedRow.Cells[4].Text
                                +GridView_showhotel.SelectedRow.Cells[5].Text
                                +GridView_showhotel.SelectedRow.Cells[6].Text;

        ((Order)Session["Order"]).Hotel.HotelID = GridView_showhotel.SelectedValue.ToString();
        ((Order)Session["Order"]).Hotel.Name = GridView_showhotel.SelectedRow.Cells[2].Text;
        
        ((Order)Session["Order"]).Hotel.Province = GridView_showhotel.SelectedRow.Cells[3].Text;
        ((Order)Session["Order"]).Hotel.City = GridView_showhotel.SelectedRow.Cells[4].Text;
        ((Order)Session["Order"]).Hotel.County = GridView_showhotel.SelectedRow.Cells[5].Text;
        ((Order)Session["Order"]).Hotel.Address = GridView_showhotel.SelectedRow.Cells[6].Text;
        ((Order)Session["Order"]).Hotel.Telephonenumber = GridView_showhotel.SelectedRow.Cells[7].Text;


        sqlcon.Open();
        ShowHotelFreeRoom(sqlcon);
        sqlcon.Close();
        GridView_showhotel.Visible = false;

    }
}